<?php

namespace app\api\controller;
use app\common\logic\GoodsLogic;
use app\common\logic\GoodsPromFactory;
use think\Db;
use think\Request;
use think\Validate;
use think\Session;
class Goods extends ApiCommon{
	
	public function _initialize()
    {
    	
    	$this->nocheckArr = ['categoryList','twocategoryList','goodsList','search','goodsInfo','comment'];
        parent::_initialize();
	}
    /**
     * 一级分类显示
     */
    public function categoryList(){
        
		$goods_category = M('goods_category')->where('is_show=1 and level=1')->cache(true)->field('id,mobile_name,parent_id,level')->order("sort_order desc")->select(); // 键值分类数组
		//return json_encode(['status'=>'ok','arr'=>$goods_category]);//$this->ajaxReturn(['error'=>'ok','arr'=>$goods_category]);//
		$this->returnMsg('ok','',$goods_category);
    }
	
	/**
	 * 二级分类显示
	 * */
	public function twocategoryList(){
        
		$request = Request::instance();
		$data = $request->param();
		
		//catid 大类编号
		$rule = [
		    'catid'  => 'require'
		];
		
		$msg = [
		    'catid.require' => 'catid not find'
		];
		
		
		$validate = new Validate($rule, $msg);
		$result   = $validate->check($data);
		
		if(!$result){
//			return json_encode(['status'=>$validate->getError()]);
			$this->returnMsg(-1,$validate->getError());
		}
		
		$catid = $data['catid'];
		$goodsLogic = new GoodsLogic();
		
		// 分类菜单显示
    	$goodsCate = M('GoodsCategory')->where("id", $catid)->find();// 当前分类
    	$cateArr = $goodsLogic->get_goods_cate($goodsCate);		
//		return json_encode(['status'=>'ok','arr'=>$cateArr]);
		$this->returnMsg('ok','',$cateArr);
    }
	
	//商品列表
	public function goodsList(){

    	$id = I('id/d',1); 				 // 当前分类id
    	$sort = I('sort','goods_id'); 	 // 排序数据库字段
    	$sort_asc = I('sort_asc','asc'); // 排序规则  	desc asc
		$page = I('page/d',0);
    	 
    	// 帅选 品牌 规格 属性 价格
    	$cat_id_arr = getCatGrandson ($id);
        $goods_where = ['is_on_sale' => 1, 'exchange_integral' => 0,'cat_id'=>['in',$cat_id_arr]];
    	$filter_goods_id = Db::name('goods')->where($goods_where)->cache(true)->getField("goods_id",true);
    	
    	$count = count($filter_goods_id);
		$pagesize = C('PAGESIZE');
		$startpage = $page * $pagesize;
		$endpage = $pagesize;
		$goods_list = [];
    	if($count > 0)
    	{
    		$goods_list = M('goods')->where("goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($startpage.','.$endpage)->select();
    	}
    	
//  	return json_encode(['status'=>'ok','arr'=>$goods_list]);
		$this->returnMsg('ok','',$goods_list);
	}
	
	
	/**
     * 商品搜索列表页
     */
    public function search(){
    	$id = I('id/d',1); 				 // 当前分类id
    	$sort = I('sort','goods_id'); 	 // 排序数据库字段
    	$sort_asc = I('sort_asc','asc'); // 排序规则  	desc asc
		$page = I('page/d',0);
        $q = urldecode(trim(I('q',''))); // 关键字搜索

        $where  = array('is_on_sale' => 1);
        $where['exchange_integral'] = 0;//不检索积分商品

        if($q) $where['goods_name'] = array('like','%'.$q.'%');
        
    	$goodsLogic = new GoodsLogic();
    	$filter_goods_id = M('goods')->where($where)->cache(true)->getField("goods_id",true);

        $count = count($filter_goods_id);
		$pagesize = C('PAGESIZE');
		$startpage = $page * $pagesize;
		$endpage = $pagesize;
		$goods_list = [];
    	if($count > 0)
    	{
    		$goods_list = M('goods')->where("goods_id","in", implode(',', $filter_goods_id))->order("$sort $sort_asc")->limit($startpage.','.$endpage)->select();
    	}
    	
//  	return json_encode(['status'=>'ok','arr'=>$goods_list]);
		$this->returnMsg('ok','',$goods_list);
    }
	
    /**
     * 商品详情页
     */
    public function goodsInfo(){
    
        $goodsLogic = new GoodsLogic();
		
        $goods_id = I("id/d");
		$user_id = I("uid/d",0);
		
        $goodsModel = new \app\common\model\Goods();
        $goods = $goodsModel::get($goods_id);
		
        if(empty($goods) || ($goods['is_on_sale'] == 0) || ($goods['is_virtual']==1 && $goods['virtual_indate'] <= time())){
        	//商品已经下架
            return json_encode(['status'=>'-100']);
        }
        $goodsPromFactory = new GoodsPromFactory();
        if (!empty($goods['prom_id']) && $goodsPromFactory->checkPromType($goods['prom_type'])) {
        	//根据商品的类型额外获得商品的其他属性。比如说 拼团，抢购等
            $goodsPromLogic = $goodsPromFactory->makeModule($goods, null);//这里会自动更新商品活动状态，所以商品需要重新查询
            $goods = $goodsPromLogic->getGoodsInfo();//上面更新商品信息后需要查询
        }
		
		//如果是品牌获得品牌信息
        if($goods['brand_id']){
            $brnad = M('brand')->where("id", $goods['brand_id'])->find();
            $goods['brand_name'] = $brnad['name'];
        }
        $goods_images_list = M('GoodsImages')->where("goods_id", $goods_id)->select(); // 商品 图册
        $goods_attr_list = Db::query('select tp_goods_attr.*,tp_goods_attribute.attr_name from tp_goods_attr,tp_goods_attribute where tp_goods_attr.attr_id = tp_goods_attribute.attr_id and goods_id = ?',[$goods_id]);
		
		//规格信息
		$filter_spec = $goodsLogic->get_spec($goods_id);
		//规格 对应 价格 库存表
        $spec_goods_price  = M('spec_goods_price')->where("goods_id", $goods_id)->getField("key,price,store_count,item_id"); 
		//评论统计
        $commentStatistics = $goodsLogic->commentStatistics($goods_id);// 获取某个商品的评论统计
      	$goods['sale_num'] = M('order_goods')->where(['goods_id'=>$goods_id,'is_send'=>1])->count();
		
        //当前用户收藏
        $collect = [];
        if($user_id>0){
        	$collect = M('goods_collect')->where(array("goods_id"=>$goods_id ,"user_id"=>$user_id))->count();
        }      
 
        $goods_collect_count = M('goods_collect')->where(array("goods_id"=>$goods_id))->count(); //商品收藏数


		//arr 商品信息
		//imgarr 轮播图片
		//attrlist 商品属性
		//filter_spec 规格信息
		//spec_goods_price 不同的规格对应的价格
		//commentStatistics 评论统计 （好评多少条  差评多少条等）
		//collect 收藏列表
		//collectcount  收藏人数
//		return json_encode(['status'=>'ok','arr'=>$goods,'imgarr'=>$goods_images_list,
//		'attrlist'=>$goods_attr_list,'filter_spec'=>$filter_spec,
//		'spec_goods_price'=>$spec_goods_price,'commentStatistics'=>$commentStatistics,
//		'collect'=>$collect,
//		'goods_collect_count'=>$goods_collect_count]);
		
		
		$backArr = ['arr'=>$goods,'imgarr'=>$goods_images_list,
		'attrlist'=>$goods_attr_list,'filter_spec'=>$filter_spec,
		'spec_goods_price'=>$spec_goods_price,'commentStatistics'=>$commentStatistics,
		'collect'=>$collect,
		'goods_collect_count'=>$goods_collect_count];
		
		$this->returnMsg('ok','',$backArr);
    }


    /*
     * ajax获取商品评论
     */
    public function comment()
    {
    	//删减查询字段
        $goods_id = I("goods_id/d", 0);
        $commentType = I('commentType', '1'); // 1 全部 2好评 3 中评 4差评
        $page = I('page', 0); 				  // 分页
        
        if ($commentType == 5) {
            $where = array(
                'goods_id' => $goods_id, 'parent_id' => 0, 'img' => ['<>', ''],'is_show'=>1
            );
        } else {
            $typeArr = array('1' => '0,1,2,3,4,5', '2' => '4,5', '3' => '3', '4' => '0,1,2');
            $where = array('is_show'=>1,'goods_id' => $goods_id, 'parent_id' => 0, 'ceil((deliver_rank + goods_rank + service_rank) / 3)' => ['in', $typeArr[$commentType]]);
        }
        $count = M('Comment')->where($where)->count();
        $page_count = C('PAGESIZE');
        $startpage = $page*$page_count;
        $list = M('Comment')
            ->alias('c')
            ->join('__USERS__ u', 'u.user_id = c.user_id', 'LEFT')
            ->where($where)
            ->order("add_time desc")
            ->limit($page->$startpage . ',' . $page_count)
			->field('tp_comment.*')
            ->select();
        $replyList = M('Comment')->where(['goods_id' => $goods_id, 'parent_id' => ['>', 0]])->order("add_time desc")->select();
        foreach ($list as $k => $v) {
            $list[$k]['img'] = unserialize($v['img']); // 晒单图片
            $replyList[$v['comment_id']] = M('Comment')->where(['is_show' => 1, 'goods_id' => $goods_id, 'parent_id' => $v['comment_id']])->order("add_time desc")->select();
        }
		
		
//		return json_encode(['status'=>'ok',
//			'arr'=>$list,							//商品评论
//			'commentType'=>$commentType,			//1 全部 2好评 3 中评 4差评 5晒图
//			'replyList'=>$replyList,				// 管理员回复
//			'count'=>$count						//页数
//		]);

		$backArr = ['arr'=>$list,							//商品评论
			'commentType'=>$commentType,			//1 全部 2好评 3 中评 4差评 5晒图
			'replyList'=>$replyList,				// 管理员回复
			'count'=>$count];
		$this->returnMsg('ok','',$backArr);
    }
    
    /*
     * 获取商品规格
     */
    public function goodsAttr(){
        $goods_id = I("get.goods_id/d",0);
        $goods_attribute = M('GoodsAttribute')->getField('attr_id,attr_name'); // 查询属性
        $goods_attr_list = M('GoodsAttr')->where("goods_id", $goods_id)->select(); // 查询商品属性表
        $this->assign('goods_attr_list',$goods_attr_list);
        $this->assign('goods_attribute',$goods_attribute);
        return $this->fetch();
    }



     



    /**
     * 品牌街
     */
    public function brandstreet()
    {
        $getnum = 9;   //取出数量
        $goods=M('goods')->where(array('is_recommend'=>1,'is_on_sale'=>1))->page(1,$getnum)->cache(true,TPSHOP_CACHE_TIME)->select(); //推荐商品
        for($i=0;$i<($getnum/3);$i++){
            //3条记录为一组
            $recommend_goods[] = array_slice($goods,$i*3,3);
        }
        $where = array(
            'is_hot' => 1,  //1为推荐品牌
        );
        $count = M('brand')->where($where)->count(); // 查询满足要求的总记录数
        $Page = new Page($count,20);
        $brand_list = M('brand')->where($where)->limit($Page->firstRow.','.$Page->listRows)->order('sort desc')->select();
        $this->assign('recommend_goods',$recommend_goods);  //品牌列表
        $this->assign('brand_list',$brand_list);            //推荐商品
        $this->assign('listRows',$Page->listRows);
        if(I('is_ajax')){
            return $this->fetch('ajaxBrandstreet');
        }
        return $this->fetch();
    }
    
    /**
     * 用户收藏某一件商品
     * @param type $goods_id
     */
    public function collect_goods($goods_id){
        $goods_id = I('goods_id/d',0);
		$user_id = I('uid/d',0);
        $goodsLogic = new GoodsLogic();
        $result = $goodsLogic->collect_goods($user_id,$goods_id);
		//status = 1 成功
        exit(json_encode($result));
    }
}